<?php
namespace app\index\controller;
use app\index\model\AuthRule as AuthRuleModel;
use app\index\controller\Common;
/**
* 权限控制器
*   @author 于江 2017年3月30日
*   邮箱935315164@qq.com
*/
class AuthRule extends Common
{
	
			// 友情链接列表
		public function index(){
			$authRuleRes=new AuthRuleModel();
			if(request()->isPost()){
            $sorts=input('post.');
            foreach ($sorts as $k => $v) {
                $authRuleRes->update(['id'=>$k,'sort'=>$v]);
            }
            $this->success('更新排序成功！',url('index'));
            return;
        }
	     	
	     	$authRes=$authRuleRes->AuthRuleTree();
	     	$this->assign('authRes',$authRes);
        	return $this->fetch();
    	}
			// 添加
	public function add(){

			if (request()->isPost()) {
				$data=input('post.');
				$plevel=db('auth_rule')->where('id',$data['pid'])->field('level')->find();
				if ($plevel) {
					$data['level']=$plevel['level']+1;
				}else{
					$data['level']=0;//顶级权限
				}
				
				$add=db('auth_rule')->insert($data);
				 $validate = \think\Loader::validate('AuthRule');
	            if(!$validate->scene('add')->check($data)){
	                $this->error($validate->getError());
	            }
				if ($add) {
					$this->success('添加权限成功！',url('index'));
				}else{
					$this->error('添加权限失败');
				}
				return;
			}
		$authRuleRes=new AuthRuleModel();
	 	$authRes=$authRuleRes->AuthRuleTree();
	 	$this->assign('authRes',$authRes);
		return $this->fetch();
	}
	// 编辑
	public function edit()
	{
		if (request()->isPost()) {
			$data=input('post.');
			$plevel=db('auth_rule')->where('id',$data['pid'])->field('level')->find();
				if ($plevel) {
					$data['level']=$plevel['level']+1;
				}else{
					$data['level']=0;//顶级权限
				}
			$save=db('auth_rule')->update($data);
			 $validate = \think\Loader::validate('AuthRule');
	            if(!$validate->scene('add')->check($data)){
	                $this->error($validate->getError());
	            }
			if ($save) {
				$this->success('修改权限成功！',url('index'));

			}else{
				$this->error('修改权限失败');
			}
			return;
		}
		$authRuleRes=new AuthRuleModel();
	 	$authRes=$authRuleRes->AuthRuleTree();
	 	$authRules=$authRuleRes->find(input('id'));//当前的
	 	$this->assign('authRes',$authRes);
	 	$this->assign('authRules',$authRules);

		return $this->fetch();
	}
	// 删除
	 public function del(){
	 		$authRuleRes=new AuthRuleModel();
	 		$a=$authRuleRes->getparentid(input('id'));
	 		$auth=$authRuleRes->getchilrenid(input('id'));
	 		$auth[]=input('id');
	 		$del=AuthRuleModel::destroy($auth);
	 		if ($del) {
	 			$this->success('删除权限成功！',url('index'));
	 		}else{
				$this->error('删除权限失败');
			}
    }

















}
